import Clipboard from 'clipboard'

export function isDef(v) {
  return v !== undefined && v !== null
}

export function dataURLToImage(dataURL) {
  return new Promise((resolve) => {
    const img = new Image()
    img.onload = () => resolve(img)
    img.src = dataURL
  })
}

export function canvastoFile(canvas, type, quality) {
  return new Promise((resolve) => canvas.toBlob((blob) => resolve(blob), type, quality))
}

export const fileToDataURL = (file) => {
  return new Promise((resolve) => {
    const reader = new FileReader()
    reader.onloadend = (e) => resolve(e.target.result)
    reader.readAsDataURL(file)
  })
}

export const copyToClipboard = () => {
  let clipboard = new Clipboard('.copy')
  clipboard.on('success', (e) => {
    showToast.success('复制成功', { icon: () => null, 'custom-class': 'copy-toast' })
    // 释放内存
    clipboard.destroy()
  })
  clipboard.on('error', (e) => {
    // 不支持复制
    console.log('该浏览器不支持自动复制', e)
    // 释放内存
    clipboard.destroy()
  })
}
// 动态引入图片
export const DynamicImg = (filename) => {
  return new URL(`../assets/img/${filename}`, import.meta.url).href
}
// query序列化
export const p2q = (param) => {
  if (param == undefined) return ''
  let query = ''
  Object.keys(param).forEach((e, i) => {
    query += `${i === 0 ? '?' : '&'}${e}=${param[e]}`
  })
  return query
}

// 获取queryObj
export function getQueryObj(url) {
  let arr = decodeURIComponent(url).split('?')[1].split('#')[0].split('&')
  const resObj = {}
  arr.forEach((item) => {
    let [key, value = ''] = item.split('=')
    resObj[key] = value
  })
  return resObj
}

// 是否为移动端
export function isMobile() {
  if (
    window.navigator.userAgent.match(
      /(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i
    )
  ) {
    return true // 移动端
  } else {
    return false // PC端
  }
}
/**
 * @description 格式化字典
 * @returns
 */
export const formatDictionary = (list) => {
  return list.map((v) => ({
    value: v.dictionaryCode,
    text: v.dictionaryNameCn
  }))
}
/**
 * 数组对象去重
 * @param {Array}  arr    要去重的数组对象
 * @param {String} key    对象中的唯一标识符
 *
 * @return {Array} 去重后的数组
 */
export function arrayObjDeWeight(arr, key) {
  let newArr = JSON.parse(JSON.stringify(arr))
  const obj = {}
  newArr = newArr.reduce((item, next) => {
    if (typeof key === 'object') {
      if (!obj[next[key[0]]] || !obj[next[key[1]]]) {
        obj[next[key[0]]] = item.push(next)
        obj[next[key[1]]] = true
      }
    } else {
      if (!obj[next[key]]) {
        obj[next[key]] = item.push(next)
      }
    }
    return item
  }, [])
  return newArr
}
export const hasPermission = (route, roles) => {
  if (route.meta && route.meta.code) {
    return roles.some((role) => route.meta.code.indexOf(role.id) >= 0)
  } else {
    return true
  }
}

/*
  过滤路由表 返回符合用户角色的路由
  @param Router 路由
  @param roles 用户角色
*/
export const filterRouter = (reouter, roles) => {
  let filterRouter = reouter.filter((route) => {
    if (hasPermission(route, roles)) {
      return true
    }
    return false
  })
  return filterRouter
}
